<template>
  <div>
    <div class="sys-role-index">
      <el-container>
        <el-main>
          <el-row >
            <el-form :inline="true" size="small" :model="searchForm" class="demo-form-inline" @keyup.enter.native="searchQuery()" @submit.native.prevent>
              <el-form-item>
                <el-button  type="primary"  icon="el-icon-plus" @click="addRole()" v-if="permissions.indexOf('role_sysRole_add') > -1">添加</el-button>
              </el-form-item>
              <el-form-item>
                <el-input v-model="searchForm.name" placeholder="请输入角色名" />
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-search" type="primary"  @click="searchQuery()">查询</el-button>
                <el-button class="margin-left-10" icon="el-icon-delete" @click="reset()">清空</el-button>
              </el-form-item>
              <el-tooltip effect="dark" content="刷新" placement="top-start">
                <el-button size="small" style="float: right;" class="float-right" icon="el-icon-refresh" @click="searchQuery()" circle></el-button>
              </el-tooltip>
            </el-form>
          </el-row>
          <el-table
            border
            show-header
            stripe
            size="mini"
            :data="roleList"
            @selection-change="sysRoleSelectionChange"
            highlight-current-row ref="sysRoleTable">
            <el-table-column label="序号" width="50" align="center">
              <template slot-scope="scope">
                <span>{{scope.$index+(pageInfo.current - 1) * pageInfo.pageSize + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="角色名" align="center" show-overflow-tooltip/>
            <el-table-column prop="code" label="角色编码" align="center" show-overflow-tooltip/>
            <el-table-column prop="description" label="描述" align="center" show-overflow-tooltip/>
            <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip/>
            <el-table-column label="操作" fixed="right" align="center">
              <template slot-scope="scope" >
                <el-button type="text" size="small" icon="el-icon-view" v-if="permissions.indexOf('role_sysRole_query') > -1" @click="look(scope.row)">查看</el-button>
                <el-button type="text" size="small" icon="el-icon-edit" @click="editRole(scope.row)" v-if="scope.row.isEdit == 0 && permissions.indexOf('role_sysRole_edit') > -1">编辑</el-button>
                <el-button type="text" size="small" icon="el-icon-delete" @click="del(scope.row)" v-if="scope.row.isEdit == 0 && permissions.indexOf('role_sysRole_del') > -1">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-if="pageInfo.total>0"
            :style="{float: 'right', padding: '20px'}"
            class="pageBar"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageInfo.current"
            :page-sizes="[5, 10, 20, 30]"
            :page-size="pageInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total">
          </el-pagination>
        </el-main>
      </el-container>
      <el-dialog
        customClass="cstomWidth"
        :title="title"
        :visible.sync="showDialog"
        @close="close"
        append-to-body="true">
        <el-container>
          <el-main>
            <el-form
              ref="form"
              :model="form"
              label-width="90px"
              :rules="rules">
              <el-form-item label="角色名" ref="name" prop="name">
                <el-input :disabled="isLook" placeholder="请输入角色名称" v-model="form.name" maxlength="10"/>
              </el-form-item>
              <el-form-item label="角色编码" ref="code" prop="code">
               <!-- <el-input placeholder="请输入角色编码" v-model="form.code"  maxlength="20" :disabled="title == '编辑' || isLook" />-->
                <el-select placeholder="请输入角色编码" style="width: 100%" v-model="form.code" :disabled="title == '编辑' || isLook" clearable>
                  <el-option
                  v-for="item in roleCodeOption"
                  :value="item.id"
                  :key="item.id"
                  :label="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="数据权限" prop="dsType" class="form-item-tree">
                <el-select
                    :disabled="isLook"
                    placeholder="请选择"
                    v-model="form.dsType">
                  <el-option
                      v-for="item in dsTypeOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
                <div v-if="form.dsType == 4">
                  <el-tree
                      :data="orgTree"
                      show-checkbox
                      default-expand-all
                      :default-checked-keys="checkTree"
                      node-key="id"
                      ref="tree"
                      highlight-current
                      :props="defaultProps"
                      @check-change="handleCheckChange"
                      ></el-tree>
                </div>
              </el-form-item>
              <el-form-item label="描述" ref="description" prop="description">
                <el-input :disabled="isLook" maxlength="20" placeholder="请输入描述" v-model="form.description" show-word-limit/>
              </el-form-item>
            </el-form>
          </el-main>
        </el-container>
        <div slot="footer" class="dialog-footer" v-show="!isLook">
          <el-button icon="el-icon-circle-plus-outline" size="small" @click="saveForm" type="primary">确 定</el-button>
          <el-button icon="el-icon-circle-close" size="small" @click="close">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import sysRoleApi from "./api/sysRole.service";
import Mixins from "@/puzzles/tpf/mixins/index";

export default {
  mixins: [Mixins],
  components: {
  },
  data() {
    return {
      rules: {
        name: [
          {
            required: true,
            message: "角色名不能为空！"
          },
          {
            min: 4,
            max: 10,
            message: "角色名长度在 4 到 10 个英文字符.",
            trigger: "blur"
          },
          {
            pattern: /^[a-zA-Z]{1,}$/,
            message: "只允许字母",
            trigger: "blur"
          }
        ],
        code: [
          {
            required: true,
            message: "角色编码不能为空！"
          },
          {
            pattern: /^[a-zA-Z_0-9]{1,}$/,
            message: "只允许字母及下划线",
            trigger: "blur"
          }
        ],
        description: [
          {
            required: true,
            message: "描述不能为空！"
          }
        ],
        dsType: [
          {
            required: true,
            message: "数据权限不能为空！"
          }
        ]
      },
      permissions: JSON.parse(sessionStorage.getItem('permissions')),
      menuTree: [],
      title: "",
      roleList: [],
      showDialog: false,
      searchForm: {
        name: ''
      },
      form: {
        name: "",
        code: "",
        dsType:1,
        dsScope: "",
        description: ""
      },
      sysRoleId: "",
      isLook: false,
      pageInfo: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      roleCodeOption: [
        {
          id: 11+"0",
          name: "全网系统管理员"
        },
        {
          id: 1+"0"+1,
          name: "全网安全保密管理员"
        },
        {
          id: "0"+11,
          name: "全网安全审计员"
        },
        {
          id: "6"+66,
          name: "会议管理员"
        },
        {
          id: "00"+0,
          name: "普通用户"
        },

      ],
      dsTypeOptions:[
        {
          id:1,
          name:"全部"
        },
        {
          id:2,
          name:"本级"
        },
        {
          id:3,
          name:"本级及子级"
        },
        {
          id:4,
          name:"自定义"
        }
      ],
      orgTree: [
        {
          id: 1,
          label: "一级部门",
          children: [
            {
              id: 2,
              label: "二级部门",
              children: [
                {
                  label: "三级部门",
                },
              ],
            },
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "name",
      },
      checkTree: [],
    };
  },
  created() {
    this.search(this.pageInfo);
    this.getOrgTree();
  },
  methods: {
    // 查看
    look(row) {
      this.showDialog = true;
      this.title = "查看";
      this.isLook = true;
      this.form = JSON.parse(JSON.stringify(row));
    },
    // 添加
    addRole() {
      this.showDialog = true;
      this.title = "添加";
    },
    // 编辑
    editRole(row) {
      let obj = JSON.parse(JSON.stringify(row));
      this.title = "编辑";
      this.showDialog = true;
      this.form = obj;
      this.showOrgCheckTree(obj.dsScope);
    },
    // 保存
    saveForm() {
      let _this = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.dsType == 4){
            if(!this.form.dsScope){
              this.$message.error("请选择数据权限范围！");
              return;
            }
          }
          // this.showDialog = false
          if (this.title === "添加") {
            sysRoleApi.saveSysRole(this.form).then(res => {
              if (res.code == 10200) {
                this.$message.success("添加成功！");
                _this.close();
                _this.searchQuery();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else {
            let obj = {
              id: this.form.id,
              code: this.form.code,
              name: this.form.name,
              description: this.form.description,
              dsType: this.form.dsType,
              dsScope: this.form.dsScope
            };
            sysRoleApi.updateSysRoleById(obj).then(res => {
              if (res.code == 10200) {
                this.$message.success("修改成功！");
                _this.close();
                _this.searchQuery();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        }
      });
    },
    // 关闭
    close() {
      let obj = {
        name: "",
        code: "",
        dsType: 1,
        description: ""
      };
      this.form = obj;
      this.$refs["form"].resetFields();
      this.isLook = false;
      this.showDialog = false;
    },
    // 删除
    del(row) {
      this.$confirm("本操作将永久删除角色，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        sysRoleApi.deleteSysRole([row.id]).then(res => {
          if (res.data > 0) {
            this.$message.success("删除角色成功！");
            this.pageInfo.current = 1;
            this.searchQuery();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    // 改变页码
    handleSizeChange (val) {
      this.pageInfo.pageSize = val;
      this.search(this.pageInfo)
    },
    handleCurrentChange (val) {
      this.pageInfo.current = val;
      this.search(this.pageInfo)
    },
    searchQuery(){
      this.pageInfo.current = 1;
      this.search(this.pageInfo);
    },

    /**
     * 查询
     */
    search (page) {
      let _this = this;
      sysRoleApi.getSysRolePage(
        Object.assign({
          current: page.current,
          size: page.pageSize,
          name: this.searchForm.name
        })
      ).then(res => {
        _this.pageInfo.total = res.data.total;
        _this.roleList = res.data.records;
      });
    },

    /**
     * 重置
     */
    reset () {
      this.searchForm.name = '';
      this.searchQuery()
    },

    /**
     * 获取组织机构树
     */
    getOrgTree() {
      let _this = this;
      sysRoleApi.getSysOrgTree().then((res) => {
        _this.orgTree = this.leafNoChildren(res.data);
      });
    },

    /**
     * 组织机构选中
     * @param data
     */
    handleCheckChange(data) {
      let parentIds = this.$refs.tree.getHalfCheckedKeys(true);
      let keys = this.$refs.tree.getCheckedKeys();
      let arrKeys = [...parentIds, ...keys];
      this.form.dsScope = arrKeys.toString();

    },

    /**
     * 选中组织机构回显
     */
    showOrgCheckTree(checkArr){
      let intCheckArr = [];
      if(checkArr){
        checkArr = checkArr.split(",");
        checkArr.forEach(function (item) {
          intCheckArr.push(parseInt(item));
        })
        this.$nextTick(() => {
          this.checkTree = this.resolveAllChildrenNodeId(this.orgTree,intCheckArr,[]);
        });
      }
    },
    resolveAllChildrenNodeId(json, idArr, temp) {
      for (let i = 0; i < json.length; i++) {
        const item = json[i];
        if (item.children && item.children.length !== 0) {
          this.resolveAllChildrenNodeId(item.children, idArr, temp)
        } else {
          let  id = idArr.filter(id => id === item.id);
          console.log(id)
          temp.push(id)
        }
      }
      return temp;
    }

  }
};
</script>

